package coroutines.interceptor

import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.startCoroutine

class LogInterceptor : ContinuationInterceptor {
    companion object Key : CoroutineContext.Key<LogInterceptor>

    override val key = Key
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        return object : Continuation<T> {
            override val context = continuation.context

            override fun resumeWith(result: Result<T>) {
                println("LogInterceptor before resumeWith(${result.getOrNull()})")

                continuation.resumeWith(result)

                println("LogInterceptor after resumeWith(${result.getOrNull()})")
            }
        }
    }
}

fun main(){
    suspend {
        println("正在测试拦截器")
//        delay(1000)
        println("还是在测试按揭器")
        "测试"
    }.startCoroutine(object : Continuation<Any?> {
        override val context: CoroutineContext = LogInterceptor()

        override fun resumeWith(result: Result<Any?>) {
            println("Interceptor test resumeWith(${result.getOrNull()})")
        }
    })
}